package day01.com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.cj.jdbc.Driver;

public class Basedao {
	public static final String URL = "jdbc:mysql://127.0.0.1:3306/day01?";
	public static final String USER = "root";
	public static final String PASS = "123456";
	public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
	
	protected Connection conn = null;
	protected PreparedStatement ps = null;
	
	public static int excuteUpdate(String sql,Object[] param) {
		 Connection conn = null;
		 PreparedStatement ps = null;
			try {
				conn = getConn();
				ps = conn.prepareStatement(sql);
				if(param != null) {
					for (int i = 0; i < param.length; i++) {
						ps.setObject(i+1, param[i]);
					}
				}
				int num = ps.executeUpdate();//执行sql
				return num;
			} catch (SQLException e) {
				// TODO: handle exception
				e.printStackTrace();
			}finally {
				closeAll(conn, ps);
			}
		return 0;
		
	}

	private static Connection getConn() {
		// TODO Auto-generated method stub
		try {
			Class.forName(DRIVER);
			Connection conn = DriverManager.getConnection(URL,USER,PASS);
			if(conn != null) {
				System.out.println("数据库连接成功");
			}else {
				System.out.println("数据库连接失败");
			}
			return conn;
		} catch (SQLException e) {
			// TODO: handle exception
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}
	
	public static void closeAll(Connection conn,Statement ps,ResultSet rs) {
		try {
			if(rs !=null) {rs.close();}
			if(ps !=null) {ps.close();}
			if(conn !=null) {conn.close();}
		} catch (SQLException e) {e.printStackTrace();}
	}
	
	public static void closeAll(Connection conn,PreparedStatement ps) {
		try {
			if(ps !=null) {ps.close();}
			if(conn !=null) {conn.close();}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询
	 * @param sql
	 * @return ResultSet
	 * */	
	public ResultSet queryResultSet(String sql) {
		Connection conn=Basedao.getConn();//打开连接
		PreparedStatement ps= null;
		ResultSet rs=null;
		try {
			ps= conn.prepareStatement(sql);
			rs = ps.executeQuery();				
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	
}
